package org.wanda.pv.controller.basic;

import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.lang.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.wanda.pv.framework.base.Result;
import org.wanda.pv.framework.page.Pagination;
import org.wanda.pv.model.basic.Point;
import org.wanda.pv.model.basic.PointRoom;
import org.wanda.pv.service.basic.PointRoomService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author LiuXuyang
 * Created by lxy on 2018/5/10.
 */

@RestController
@RequestMapping("/basic/pointRoom")
public class PointRoomController {
    private final static Logger log = LoggerFactory.getLogger(PointRoomController.class);

    @Autowired
    Dao dao;

    @Autowired
    private PointRoomService pointRoomService;

    /**
     * @api {post} /basic/questionClass/list 分页查询所有数据
     * @apiParam {String} pageNum 当前页码(默认值为1)
     * @apiParam {String} pageSize 单页显示条数(默认值为10)
     * @apiParam {String} name 题库分类名称(默认值为空)
     * @apiGroup 题库分类
     */
    @RequestMapping(value = "/list",method = RequestMethod.POST)
    public Object list(@RequestParam(value = "pageSize",required = false,defaultValue = "1") Integer pageSize,
                       @RequestParam(value = "pageNum",required = false,defaultValue = "10") Integer pageNum,
                        PointRoom pointRoom){

        Cnd cnd = Cnd.where("delFlag", "=", false);
        String name = pointRoom.getName();
        // 分类名称
        if(Strings.isNotBlank(name)){
            cnd.and("name","like","%"+name+"%");
        }
        cnd.orderBy("createDT","desc");
        Pagination pagination = pointRoomService.listPage(pageNum, pageSize, cnd);
        List<?> list = pagination.getList();
        list.forEach(item->{
            dao.fetchLinks(item,null);
        });

        return Result.success("success",pagination);
    }


    /**
     * @api {post} /basic/questionClass/del 删除题库分类
     * @apiParam {String} id 题库ID
     * @apiGroup 题库分类
     */
    @RequestMapping(value = "/del",method = RequestMethod.POST)
    public Object del(Long id){

        try{
            Map<String, Object> hasRefer = checkHasRefer(id);
            if ((Boolean) hasRefer.get("hasRefer")) {
                return Result.error("fail", (String) hasRefer.get("msg"));
            }
            pointRoomService.del(id);
            return Result.success("success","操作成功!");
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return Result.error("fail","服务器内部错误!");
        }



    }

    /**
     * @api {post} /basic/questionClass/update 修改题库分类
     * @apiParam {String} id 题库ID
     * @apiParam {String} name 题库名称
     * @apiGroup 题库分类
     */
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public Object update(PointRoom pointRoom){
        try{
            PointRoom old = dao.fetch(PointRoom.class, pointRoom.getId());
            if (!old.getName().equals(pointRoom.getName())){
                boolean repet = isRepet(pointRoom.getName());
                if (repet){
                    return Result.error("fail", "名称重复");
                }
            }
            pointRoomService.update(pointRoom);
            return Result.success("success","操作成功!");

        }catch (Exception e){
            log.error(e.getMessage(),e);
            return Result.error("fail","服务器内部错误!");
        }
    }

    /**
     * @api {post} /basic/questionClass/add 添加题库分类
     * @apiParam {String} name 题库名称
     * @apiParam {String} companyId 企业ID
     * @apiGroup 题库分类
     */
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public Object add(PointRoom pointRoom){
        try{
                // 去重
                if (isRepet(pointRoom.getName())){
                    return Result.error("fail","题库名称重复");
                }
            pointRoomService.add(pointRoom);
                return Result.success("success","操作成功!");
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return Result.error("fail","服务器内部错误!");
        }
    }


    public boolean isRepet(String name){

        int count = dao.count(PointRoom.class, Cnd.where("name", "=", name).and("delFlag","=",false));
        if (count>0) {
            return true;
        }
        return false;
    }

    private Map<String, Object> checkHasRefer(Long id) {
        Map<String, Object> result = new HashMap<>();
        PointRoom pointRoom = dao.fetch(PointRoom.class, id);
        dao.fetchLinks(pointRoom, "points", Cnd.where("delFlag", "=", "0"));
        List<Point> points = pointRoom.getPoints();
        if (points != null && points.size() > 0) {
            result.put("hasRefer", true);
            result.put("msg", "有题目引用此数据,删除失败!");
            return result;
        }
        result.put("hasRefer", false);
        return result;
    }

    /**
     * @api {post} /basic/questionClass/getAll 获取所有题库
     * @apiGroup 题库分类
     */
    @RequestMapping(value = "/getAll",method = RequestMethod.POST)
    public Object getAll( @RequestParam(value = "name", defaultValue = "") String name){
        Cnd cnd;
        if("".equals(name)){
             cnd = Cnd.where("delFlag", "=", false);
        }else{
            cnd = Cnd.where("delFlag", "=", false).and("name", "like", "%" + name + "%");
        }
        List<PointRoom> lists=dao.query(PointRoom.class,cnd);
        return Result.success("success",lists);
    }


}
